var currentNav = "main_nav_id_1";
var chatActivated = new Boolean(0);

require([ "dojo", "dojo/_base/xhr", "dojo/on", "dojo/dom", "dojo/dom-class", "dojo/parser",
		"dojo/query", "dojo/dom-attr", "dojo/dom-style", "dojo/dom-construct", "dojo/keys",
		"dojox/widget/Standby", "dojo/fx/Toggler", "dojo/fx", "dojox/fx/text", "dojox/html",
		"dojox/validate", "dojo/_base/connect", "dijit/registry", "dojo/_base/array",
		"dojo/_base/lang", "dojo/mouse", "dojo/_base/fx", "dojox/html/_base", "dijit/DropDownMenu", "dijit/MenuSeparator",
		"dijit/MenuBarItem", "dijit/PopupMenuItem", "dijit/MenuBar", "dijit/PopupMenuBarItem",
		"dijit/form/ToggleButton", "dijit/form/ComboButton", "dijit/Menu", "dijit/MenuItem",
		"dijit/form/DropDownButton", "dijit/TooltipDialog", "dojo/NodeList-traverse",
		"dojo/NodeList-manipulate", "dojo/io/script", "dojox/cometd",
		"dojox/cometd/callbackPollTransport", "dojox/validate/us", "dojox/validate/web",
		"dijit/form/CheckBox", "dijit/form/Textarea", "dijit/form/Select", "dijit/form/TextBox",
		"dijit/form/ValidationTextBox", "dijit/form/DateTextBox", "dijit/form/TimeTextBox",
		"dijit/form/Button", "dijit/form/RadioButton", "dijit/form/Form", "dijit/form/DateTextBox",
		"dojox/form/BusyButton", "dojox/form/CheckedMultiSelect", "dojo/domReady!" ],
		function(dojo, xhr, on, dom, domClass, parser, query, domAttr, domStyle, construct, keys,
				Standby, Toggler, fx, text, html, validate, connect, registry, array, lang, mouse, baseFx) {
			
			var navLink;
			var standby = new Standby({
				target : "content-wrap"
			});
			document.body.appendChild(standby.domNode);
			parser.parse();
			query(".vis-menu-link").on("click", function(e) {
				loadVisContentPane(e.currentTarget);
			});
			
			query(".vis-menu-item").on(mouse.enter, function(e) {
				 domClass.add(e.currentTarget, "vis-menu-item-selected");
				 var subMenu = query(e.currentTarget).children("ul");
				 if(subMenu.length){
					 domStyle.set(subMenu[0], "visibility", "visible");
				 }				 
			});
			query(".vis-menu-item").on(mouse.leave, function(e) {
				 domClass.remove(e.currentTarget, "vis-menu-item-selected");
				 var subMenu = query(e.currentTarget).children("ul");
				 if(subMenu.length){
					 domStyle.set(subMenu[0], "visibility", "hidden");
				 }
			});
			
			
			
			var x = 1;
			var total = 3;
			var sliderHandle;
			initiateSlider = function(){
				var y;
				if(x > total){
					x = 1;
				}
				if(x == total){
					y = 1;
				} else {
					y = x + 1;
				}
				
				baseFx.animateProperty({
					node: dom.byId("race" + x),
					properties: {
						opacity: { start: 1, end: 0.5 }
					},
					duration: 500,
					onEnd: function(){
						baseFx.animateProperty({
							node: dom.byId("race" + (y) ),
							properties: {
								opacity: { start: 0, end: 0.5 }
							},
							duration: 500,
							onEnd: function(){
								baseFx.animateProperty({
									node: dom.byId("race" + x),
									properties: {
										opacity: { start: 0.5, end: 0 }
									},
									duration: 500,
									onEnd: function(){
										baseFx.animateProperty({
											node: dom.byId("race" + (y) ),
											properties: {
												opacity: { start: 0.5, end: 1 }
											},
											duration: 500,
											onEnd: function(){
												x++;
											}
										}).play();
									}
								}).play();
							}
						}).play();
					}
				}).play();
				
			}

			loadVisContentPane = function(target) {
				destroyWidgets();
				standby.show();
				contenturl = domAttr.get(target, "content-url");
				console.log(" handling loadContentPane using " + target + " and context url "
						+ contenturl);
				if (contenturl) {
					xhr.get({
						url : contenturl,
						load : loadContentPaneVisCallback,
						error : function() {
							dom.byId("content-wrap").innerHTML = "";
						}
					});
					domClass.remove(query(".vis-menu-item-current")[0], "vis-menu-item-current"); 
					domClass.add(query(target).closest("div")[0], "vis-menu-item-current"); 					
				} else {
					console.log("no content url provided");
				}
			}

			loadContentPaneVisCallback = function(newContent, ioargs) {
				var xhrstatus = ioargs.xhr.status;
				console.log(" xhr status : " + xhrstatus);
				html.set(dojo.byId("content-wrap"), newContent, {
					executeScripts : true,
					scriptHasHooks : false,
					renderStyles : true
				});
				standby.hide();
				if(sliderHandle){
					clearInterval(sliderHandle);
				}
				if (contenturl.indexOf("login.htm") != -1) {
					parser.parse("login_content_td");
					handleLoginSubmit();
					loadUserRegistrationpage();
				} else if(contenturl.indexOf("visHome.htm") != -1){
					parser.parse("content-wrap"); 
					hookDashboardNav();
					sliderHandle = setInterval("initiateSlider()", 10000);					
				} else if(contenturl.indexOf("contactUs.htm") != -1){
					parser.parse("content-wrap");
					handleContactUsSubmit();
				} else {		
					parser.parse("content-wrap"); 
				}

			}
			
			handleContactUsSubmit = function(){
				var regForm = dojo.byId("contactUsForm");
				dojo.connect(regForm,"onsubmit", function(e) {
					standby.show();
					var xhrArgs = {
						form : dojo.byId("contactUsForm"),
						url: '/public/vis/sendEmail.htm',
						load : handleContactUsSubmitCallback,
						error : function(error) {
							console.log("error occurred : " + error);
							standby.hide();
						}
					}										
					if(registry.byId("contactUsForm").validate()){ 
						xhr.post(xhrArgs);		
					} else {
						standby.hide();
					}
							
				});
			}
			
			handleContactUsSubmitCallback = function(data) {
				standby.hide();
				domStyle.set("contactFormMessage", "display", "inline");
				dojo.byId("contactFormMessage").innerHTML = data;
			}
			
			handleLoginSubmit = function(){
				var loginForm = dojo.byId("loginForm");
				dojo.connect(loginForm,"onsubmit", function(e) {					
					var xhrArgs = {
						form : dojo.byId("loginForm"),
						url: '/j_spring_security_check',
						load : function(data) {
							if (data.indexOf("loginPageResponse") != -1) {
								destroyWidgets();
								html.set(dojo.byId("content-wrap"), data, {
							        executeScripts: true,
							        scriptHasHooks: false,
							        renderStyles: true
							    });								
								parser.parse("login_content_td"); 
								handleLoginSubmit();
								loadUserRegistrationpage();	
								standby.hide();
							}else {
								window.location.reload();
							}
						},
						error : function(error) {
							dojo.byId("content-wrap").innerHTML = "error occurred";
							destroyWidgets();
							standby.hide();
						}
					}
					
					if(registry.byId("loginForm").validate()){ 
						standby.show();
						xhr.post(xhrArgs);
					} 
				});
			}
			
			handleUserRegistrationSubmit = function() {
				var regForm = dojo.byId("registerForm"); 
				dojo.connect(regForm,"onsubmit", function(e) {
					
					var xhrArgs = {
						form : dojo.byId("registerForm"),
						url: '/public/registerUser.htm',
						load : function(data) {
							//dojo.byId("registrationPane").innerHTML = data;
							standby.hide();
							console.log("xhrget response data: " + data);
							if (data == 'success') {
								console.log(" reloading page for consistency.. ");
								window.location.reload();
							} else {
								domStyle.set("regFormMessage", "display", "inline");
								dojo.byId("regFormMessage").innerHTML = data;
							}
						},
						error : function(error) {
							dojo.byId("contentpane").innerHTML = "";
							standby.hide();
						}
					}
										
					if(registry.byId("registerForm").validate()){ 
						xhr.post(xhrArgs);	
						standby.show();
					} 
							
				});
			}
			
			loadUserRegistrationpageCallback = function(newContent, ioargs) {
				html.set(dojo.byId("registrationPane"), newContent, {
			        executeScripts: true,
			        scriptHasHooks: false,
			        renderStyles: true
			    });
				parser.parse("registrationPane"); 
				standby.hide();
				handleUserRegistrationSubmit();
			}

			loadUserRegistrationpage = function() {
				xhr.get({
					url : '/public/showRegistrationForm.htm',
					load : loadUserRegistrationpageCallback,
					error : function(ioargs) {
						dom.byId("contentpane").innerHTML = "error occured";
					}
				});
			}
			
			destroyWidgets = function() {
				array.forEach(registry.toArray(), function(widget, i) {
					// console.log(widget.declaredClass);
					if (widget.declaredClass != 'dojox.widget.Standby' && widget.declaredClass != 'dijit._MasterTooltip') { 
						widget.destroy();
					}
				});
				// console.log(registry.length);
			}
			
			loadVisContentPane(dom.byId("primary_link"));
			
			
			hookDashboardNav = function(){
				query(".dashboard-nav-a").on("click", function(e){ 
					var contentId = domAttr.get(e.currentTarget, "content-id");
					var currentContentId = domAttr.get(query("#dashboard-nav .selected")[0], "content-id") ;
					domClass.remove(query("#dashboard-nav .selected")[0], "selected"); 
					domClass.add(query(e.currentTarget)[0], "selected");
					domStyle.set(dom.byId(currentContentId), "display", "none");
					domStyle.set(dom.byId(contentId), "display", "");
				});
			}

		});
